package com.basketball.gym.controller;


import com.basketball.gym.annotation.ApiJsonObject;
import com.basketball.gym.annotation.ApiJsonProperty;
import com.basketball.gym.annotation.MyLog;
import com.basketball.gym.pojo.ResponseData;
import com.basketball.gym.pojo.User;
import com.basketball.gym.pojo.state.ResponseState;
import com.basketball.gym.service.UserService;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.validation.constraints.Pattern;
import java.io.IOException;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 赵肖云
 * @since 2021-03-15
 */
@Api(tags = "用户管理")
@RestController
@RequestMapping("/gym/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private Logger logger;

    /**
     * 登录
     */
    @ApiOperation("登录")
    @PostMapping("/login")
    public ResponseData<User> login(@ApiJsonObject(name = "UserLogin", value = {
            @ApiJsonProperty(key = "code", description = "code")
    }) @RequestBody Map<String, String> param) {
        return userService.login(param.get("code"));
    }

    /**
     * 将从微信获取的用户信息更新到数据库
     */
    @ApiOperation("插入微信信息")
    @PreAuthorize("hasRole('user')")
    @PostMapping("/info")
    public ResponseData<User> updateInformation(@ApiJsonObject(name = "UserUpdateInformation", value = {
            @ApiJsonProperty(key = "encryptedData"),
            @ApiJsonProperty(key = "iv")
    }) @RequestBody Map<String, String> param, @ApiIgnore @ModelAttribute("activeUser") User user) {
        return userService.updateInfo(param.get("encryptedData"), param.get("iv"), user);
    }

    /**
     * 退出登录
     *
     * @param user：当前登录的用户
     * @return responseData
     */
    @ApiOperation("退出登录")
    @PreAuthorize("hasRole('user')")
    @DeleteMapping("/logout")
    public ResponseData<Object> logout(@ApiIgnore @ModelAttribute("activeUser") User user) {
        return userService.logout(user);
    }

    /**
     * 更新Token
     */
    @ApiOperation("更新Token")
    @PostMapping("refresh")
    public ResponseData<Object> refresh(@ApiJsonObject(name = "UserRefreshToken", value = {
            @ApiJsonProperty(key = "refreshToken")
    }) @RequestBody Map<String, String> param) {
        return userService.refresh(param.get("refreshToken"));
    }

    /**
     * 获取当前登录的用户信息
     */
    @ApiOperation("获取当前登录的用户信息")
    @PreAuthorize("hasRole('user')")
    @GetMapping
    public ResponseData<User> getUser(@ApiIgnore @ModelAttribute("activeUser") User user) {
        return userService.getUser(user);
    }

    @ApiOperation("上传图片")
    @PreAuthorize("hasRole('user')")
    @PostMapping("/photo")
    public ResponseData<Object> uploadPhoto(@RequestParam MultipartFile file, @ApiIgnore @ModelAttribute("activeUser") User user) {
        try {
            return userService.uploadPhoto(file, user);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseData<>(ResponseState.FILE_FORMAT_ERROR.getMessage(), ResponseState.FILE_FORMAT_ERROR.getValue());
        }
    }

    @ApiOperation("更换头像（需提供avatarUrl）")
    @PreAuthorize("hasRole('user')")
    @PutMapping("/avatar")
    public ResponseData<Object> updateAvatar(@RequestBody User user, @ApiIgnore @ModelAttribute("activeUser") User activeUser) {
        user.setId(activeUser.getId());
        return userService.updateAvatar(user);
    }

    @ApiOperation("绑定手机号时获取验证码")
    @GetMapping("/getBindCode")
    public ResponseData<Object> getBindCode(@ApiParam(name = "phone", value = "手机号", required = true)
                                            @Pattern(regexp = "^[1]([3-9])[0-9]{9}$", message = "手机号格式错误") @RequestParam String phone, @ApiIgnore @ModelAttribute("activeUser") User user) {
        return userService.getBindCode(phone, user);
    }

    @ApiOperation("修改手机号时获取验证码")
    @GetMapping("/getUpdateCode")
    public ResponseData<Object> getUpdateCode(@ApiParam(name = "phone", value = "手机号", required = true)
                                              @Pattern(regexp = "^[1]([3-9])[0-9]{9}$", message = "手机号格式错误") @RequestParam String phone, @ApiIgnore @ModelAttribute("activeUser") User user) {
        return userService.getUpdateCode(phone, user);
    }


    @MyLog(action = "绑定/修改手机号", role = "user", type = 3)
    @ApiOperation("绑定/修改手机号")
    @ApiResponses({
            @ApiResponse(message = "该手机号已经被绑定", code = 108),
            @ApiResponse(message = "验证码未获取或已过期", code = 109),
            @ApiResponse(message = "验证码错误", code = 110)
    })
    @PostMapping("/bindPhone")
    public ResponseData<Object> bindPhone(@ApiJsonObject(name = "UserBindPhone", value = {
            @ApiJsonProperty(key = "phone", description = "手机号"),
            @ApiJsonProperty(key = "code", description = "验证码")
    }) @RequestBody Map<String, Object> param, @ApiIgnore @ModelAttribute("activeUser") User user) {
        try {
            String phone = (String) param.get("phone");
            String code = (String) param.get("code");
            return userService.bindPhone(phone, code, user);
        } catch (DuplicateKeyException e) {
            logger.error("该手机号已被绑定");
            logger.error(e.getMessage());
            return new ResponseData<>(ResponseState.PHONE_IS_EXIST.getMessage(), ResponseState.PHONE_IS_EXIST.getValue());
        }
    }



}

